package com.conversationboard.controller;

import java.io.IOException;
import java.sql.SQLException;
import java.util.Date;

import javax.mail.MessagingException;
import javax.naming.NamingException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.conversationboard.controller.debug.ServletDebugInfo;
import com.conversationboard.email.Mail;
import com.conversationboard.logger.Logger;
import com.conversationboard.model.Board;
import com.conversationboard.model.Boards;
import com.conversationboard.model.Role;
import com.conversationboard.model.User;
import com.conversationboard.security.EncryptedKey;
import com.conversationboard.security.EncryptionException;

@WebServlet(name = "NewBoardAdminControllerServlet", urlPatterns = "/Admin/NewBoardAdminControllerServlet")
public class NewBoardAdminControllerServlet extends HttpServlet {

	private static final long serialVersionUID = -4047693825102438781L;


	/**
	 * This is essentially a postback request.
	 * 
	 * When we arrive here, we should have the user ID and the board ID
	 */

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");

		String action = request.getParameter("action");

		if (action.equals("user")) {

			/* We've received the submission from the first page */

			String userToMakeBoardAdmin = request.getParameter("userid");

			/*
			 * Place this back into the request and forward to the second page;
			 * we'll pick it up again when the user submits the board, in which
			 * the doGet method will be called.
			 */

			request.setAttribute("userid", userToMakeBoardAdmin);

			RequestDispatcher dispatcher = request.getRequestDispatcher("/Pages/Admin/newboardadmin2.jsp");
			dispatcher.forward(request, response);
			return;
		}

		/* If we get here, we've received the submission from the second page */

		String userToMakeBoardAdminId = (String) request.getParameter("userid");
		String userId = request.getUserPrincipal().getName();
		String boardIdString = (String) request.getParameter("targetboardid");
		int boardId = Integer.parseInt(boardIdString);

		try {

			Board board = Boards.getBoard(boardId);

			User user = User.get(userId);
			User userToMakeBoardAdmin = User.get(userToMakeBoardAdminId);

			/* Check that users have appropriate authority */

			String key = request.getParameter("key");
			EncryptedKey encryptedKey = new EncryptedKey();

			if (!encryptedKey.isValid(key, user.getLoginId())) {
				Logger.log(new Date(), "Part 1 of error: " + this.getClass().getName(), user);
				String postRequest = ServletDebugInfo.getRawRequest(request);
				Logger.log(new Date(), "Part 2 of error:\n\n" + postRequest, user);
				return;
			}

			Role userRole = user.getRole();
			Role userToMakeBoardAdminRole = userToMakeBoardAdmin.getRole();

			/* Make sure the user is registered */

			if (userToMakeBoardAdminRole == Role.Anonymous) {
				String message = "This user is not registered; I cannot make them a board administrator";
				request.setAttribute("message", message);
				RequestDispatcher dispatcher = request.getRequestDispatcher("/Pages/messagepage.jsp");
				dispatcher.forward(request, response);
				return;
			}

			/*
			 * Make sure board admins can't rewrite site admins as only board
			 * admins.
			 * 
			 * 26-MAR-2007 - now irrelevant as only site admins can create board
			 * admins.
			 */

			if (userToMakeBoardAdmin.isSiteAdmin()) {
				String message = "This user is a site administrator.";
				request.setAttribute("message", message);
				RequestDispatcher dispatcher = request.getRequestDispatcher("/Pages/messagepage.jsp");
				dispatcher.forward(request, response);
				return;
			}

			/* You must be a site administrator create a board admin */

			if (userRole == Role.SiteAdmin) {
				userToMakeBoardAdmin.makeBoardAdmin(boardId);
			} else {
				String message = "You do not have appropriate privileges to perform this operation.";
				request.setAttribute("message", message);
				RequestDispatcher dispatcher = request.getRequestDispatcher("/Pages/messagepage.jsp");
				dispatcher.forward(request, response);
				return;
			}

			String message = "User " + userToMakeBoardAdmin.getDisplayName() + " is now an administrator of the board: " + board.getName();

			Mail mail = new Mail();
			mail.sendToSiteAdmins("New Site Administrator", message);

			request.setAttribute("message", message);
			RequestDispatcher dispatcher = request.getRequestDispatcher("/Pages/messagepage.jsp");
			dispatcher.forward(request, response);

		} catch (SQLException e) {
			throw new ServletException(e);
		} catch (MessagingException e) {
			throw new ServletException(e);
		} catch (NamingException e) {
			throw new ServletException(e);
		} catch (EncryptionException e) {
			throw new ServletException(e);
		}

	}

}
